<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-overlay">
      <view class="loading-content">
        <view class="loading-icon">
          <uni-icons type="spinner-cycle" size="30" color="#3B82F6"></uni-icons>
        </view>
        <text class="loading-text">数据加载中...</text>
      </view>
    </view>

    <view v-else>
      <!-- 导航栏 -->
      <view class="nav-bar">
        <view class="nav-item" :class="{ active: currentView === 'day' }" @click="switchView('day')">
          今日血压
        </view>
        <view class="nav-item" :class="{ active: currentView === 'week' }" @click="switchView('week')">
          本周趋势
        </view>
      </view>

      <!-- 今日血压视图 -->
      <view v-if="currentView === 'day'" class="day-view">
        <!-- 血压概览卡片 -->
        <view class="card">
          <view class="card-header">
            <text class="title">今日血压监测</text>
            <view class="stats">
              <text class="stat-value">{{ bpData.day.avgValue }}</text>
              <text class="stat-label">平均血压</text>
            </view>
          </view>

          <!-- 血压图表 -->
          <view class="qiun-charts">
            <qiun-data-charts v-if="bpDayData" type="area" :opts="bpAreaOpts" :chartData="bpDayData" />
          </view>

          <!-- 血压数据汇总 -->
          <view class="bp-summary">
            <view class="bp-item">
              <text class="bp-label">最高血压</text>
              <text class="bp-value">{{ bpData.day.highValue }}</text>
              <text class="bp-time">{{ bpData.day.highTime }}</text>
            </view>
            <view class="bp-divider"></view>
            <view class="bp-item">
              <text class="bp-label">最低血压</text>
              <text class="bp-value">{{ bpData.day.lowValue }}</text>
              <text class="bp-time">{{ bpData.day.lowTime }}</text>
            </view>
          </view>
        </view>

        <!-- 血压分级卡片 -->
        <view class="card bp-level-card">
          <view class="card-header">
            <text class="title">血压分级</text>
          </view>
          <view class="level-indicator">
            <view class="level-bar">
              <view class="level-segment low" :style="{ flex: 2 }"></view>
              <view class="level-segment normal" :style="{ flex: 3 }"></view>
              <view class="level-segment high" :style="{ flex: 2 }"></view>
              <view class="level-segment very-high" :style="{ flex: 1 }"></view>
            </view>
            <view class="level-labels">
              <text class="level-label">偏低</text>
              <text class="level-label">正常</text>
              <text class="level-label">偏高</text>
              <text class="level-label">危险</text>
            </view>
            <view class="level-marker" :style="{ left: bpData.day.levelPosition + '%' }">
              <view class="marker-dot"></view>
              <text class="marker-text">您的血压</text>
            </view>
          </view>
        </view>

        <!-- 医生建议卡片 -->
        <view class="card advice-card">
          <view class="card-header">
            <text class="title">医生建议</text>
          </view>
          <text class="advice-text">{{ bpData.day.advice }}</text>
        </view>
      </view>

      <!-- 本周血压趋势视图 -->
      <view v-else class="week-view">
        <!-- 周血压趋势 -->
        <view class="card">
          <view class="card-header">
            <text class="title">本周血压趋势</text>
            <view class="stats">
              <text class="stat-value">{{ bpData.week.avgValue }}</text>
              <text class="stat-label">周平均</text>
            </view>
          </view>
          <view class="qiun-charts">
            <qiun-data-charts type="line" :opts="bpLineOpts" :chartData="bpWeekData" />
          </view>
        </view>

        <!-- 周血压数据汇总 -->
        <view class="card">
          <view class="card-header">
            <text class="title">本周血压数据</text>
          </view>
          <view class="week-bp-grid">
            <view class="week-bp-item" v-for="(day, index) in bpData.week.days" :key="index">
              <text class="week-day">{{ day.name }}</text>
              <text class="week-value" :class="getBpClass(day.value)">{{ day.value }}</text>
              <text class="week-time">{{ day.time }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useHealthData } from '../../../store/modules/useHealthData'
import { get } from '@/utils/request'
// import { uniIcons } from '@dcloudio/uni-ui'

const healthDataStore = useHealthData()

// 视图状态
const currentView = ref('day')
const isLoading = ref(true)

// 血压数据
const bpData = ref({
  day: {
    avgValue: "0/0 mmHg",
    highValue: "0/0 mmHg",
    highTime: "--:--",
    lowValue: "0/0 mmHg",
    lowTime: "--:--",
    levelPosition: 37.5,
    advice: "暂无数据"
  },
  week: {
    avgValue: "0/0 mmHg",
    days: [
      { name: "周一", value: "0/0", time: "--:--", systolic: 0, diastolic: 0 },
      { name: "周二", value: "0/0", time: "--:--", systolic: 0, diastolic: 0 },
      { name: "周三", value: "0/0", time: "--:--", systolic: 0, diastolic: 0 },
      { name: "周四", value: "0/0", time: "--:--", systolic: 0, diastolic: 0 },
      { name: "周五", value: "0/0", time: "--:--", systolic: 0, diastolic: 0 },
      { name: "周六", value: "0/0", time: "--:--", systolic: 0, diastolic: 0 },
      { name: "周日", value: "0/0", time: "--:--", systolic: 0, diastolic: 0 }
    ]
  }
})

const bpAreaOpts = ref({
  color: ["#EE6666"],
  padding: [15, 15, 10, 15],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED",
    boundaryGap: "justify"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    splitNumber: 4,
    data: [{
      min: 70,
      max: 180,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA",
      format: val => `${val} mmHg`
    }]
  },
  extra: {
    area: {
      type: "curve",
      opacity: 0.1,
      addLine: true,
      width: 3,
      gradient: true,
      activeType: "hollow"
    },
    markLine: {
      type: "dash",
      dashLength: 4,
      data: [
        { value: 140, lineColor: "#FF6B6B", lineWidth: 1, labelColor: "#FF6B6B", labelFontSize: 20 },
        { value: 90, lineColor: "#3B82F6", lineWidth: 1, labelColor: "#3B82F6", labelFontSize: 20 }
      ]
    }
  }
})

const bpLineOpts = ref({
  color: ["#EE6666", "#3B82F6"],
  padding: [15, 15, 10, 15],
  enableScroll: false,
  legend: {
    position: "top",
    margin: 10
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    splitNumber: 4,
    data: [{
      min: 70,
      max: 160,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA",
      format: val => `${val} mmHg`
    }]
  },
  extra: {
    line: {
      type: "curve",
      width: 3,
      activeType: "h hollow"
    }
  }
})

// 图表数据
const bpDayData = computed(() => {
  if (bpData.value.day.chartData) {
    return bpData.value.day.chartData;
  }
  return {
    categories: ["6:00", "9:00", "12:00", "15:00", "18:00", "21:00", "24:00"],
    series: [
      {
        name: "收缩压",
        data: [
          bpData.value.day.min || 0,
          bpData.value.day.avg || 0,
          bpData.value.day.max || 0,
          bpData.value.day.avg || 0,
          bpData.value.day.max || 0,
          bpData.value.day.avg || 0,
          bpData.value.day.min || 0
        ]
      }
    ]
  }
})

const bpWeekData = computed(() => ({
  categories: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
  series: [
    {
      name: "收缩压",
      data: bpData.value.week.days.map(item => item.systolic)
    },
    {
      name: "舒张压",
      data: bpData.value.week.days.map(item => item.diastolic)
    }
  ]
}))

// 方法
const switchView = (view) => {
  currentView.value = view
  loadData()
}

const getBpClass = (value) => {
  const [systolic, diastolic] = value.split('/').map(Number)
  if (systolic >= 140 || diastolic >= 90) return 'high'
  if (systolic <= 90 || diastolic <= 60) return 'low'
  return 'normal'
}

// 加载数据
const loadData = async () => {
  try {
    isLoading.value = true
    const userId = healthDataStore.getCurUserId 

    const res = await get(
      `/health/${userId}/statistics?period=${currentView.value}&type=bloodPressure`,
      'api/v1'
    )

    if (res.code === 200 && res.data) {
      if (currentView.value === 'day') {
        const [avgSystolic, avgDiastolic] = res.data.avgValue.split('/').map(v => parseInt(v));
        const [maxSystolic, maxDiastolic] = res.data.highValue.split('/').map(v => parseInt(v));
        const [minSystolic, minDiastolic] = res.data.lowValue.split('/').map(v => parseInt(v));

        bpData.value.day = {
          avgValue: res.data.avgValue,
          highValue: res.data.highValue,
          highTime: res.data.highTime,
          lowValue: res.data.lowValue,
          lowTime: res.data.lowTime,
          levelPosition: res.data.levelPosition,
          advice: res.data.advice,
          avg: avgSystolic,
          max: maxSystolic,
          min: minSystolic,
          chartData: res.data.chartData
        }
      } else {
        bpData.value.week = {
          ...bpData.value.week,
          ...res.data
        }
      }
    }
  } catch (error) {
    console.error('Failed to load blood pressure data:', error)
    uni.showToast({
      title: '数据加载失败',
      icon: 'none'
    })
  } finally {
    // 添加一个小延迟，确保数据完全准备好
    setTimeout(() => {
      isLoading.value = false
    }, 300)
  }
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadData()
})

// 监听视图切换
watch(currentView, async () => {
  await loadData()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #F7F8FA;
  min-height: 100vh;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .nav-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    transition: all 0.3s;

    &.active {
      color: #EE6666;
      font-weight: 500;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 80rpx;
        height: 4rpx;
        background-color: #EE6666;
        border-radius: 2rpx;
      }
    }
  }
}

/* 卡片通用样式 */
.card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;

  .title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }

  .stats {
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .stat-value {
      font-size: 28rpx;
      font-weight: 500;
      color: #EE6666;
    }

    .stat-label {
      font-size: 24rpx;
      color: #999;
      margin-top: 4rpx;
    }
  }
}

/* 血压数据汇总 */
.bp-summary {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;

  .bp-item {
    flex: 1;
    text-align: center;

    .bp-label {
      font-size: 26rpx;
      color: #999;
      display: block;
    }

    .bp-value {
      font-size: 36rpx;
      font-weight: 500;
      color: #333;
      display: block;
      margin: 8rpx 0;
    }

    .bp-time {
      font-size: 24rpx;
      color: #999;
      display: block;
    }
  }

  .bp-divider {
    width: 1rpx;
    background-color: #F0F0F0;
    margin: 0 20rpx;
  }
}

/* 血压分级卡片 */
.bp-level-card {
  .level-indicator {
    position: relative;
    margin-top: 40rpx;

    .level-bar {
      display: flex;
      height: 24rpx;
      border-radius: 12rpx;
      overflow: hidden;

      .level-segment {
        &.low {
          background-color: #93C5FD;
        }

        &.normal {
          background-color: #91CB74;
        }

        &.high {
          background-color: #FAC858;
        }

        &.very-high {
          background-color: #EE6666;
        }
      }
    }

    .level-labels {
      display: flex;
      justify-content: space-between;
      margin-top: 16rpx;

      .level-label {
        font-size: 24rpx;
        color: #999;
      }
    }

    .level-marker {
      position: absolute;
      top: -40rpx;
      transform: translateX(-50%);
      text-align: center;

      .marker-dot {
        width: 16rpx;
        height: 16rpx;
        background-color: #EE6666;
        border-radius: 50%;
        margin: 0 auto 8rpx;
      }

      .marker-text {
        font-size: 24rpx;
        color: #EE6666;
      }
    }
  }
}

/* 医生建议卡片 */
.advice-card {
  .advice-text {
    font-size: 26rpx;
    color: #666;
    line-height: 1.6;
  }
}

/* 周血压数据网格 */
.week-bp-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-top: 20rpx;

  .week-bp-item {
    padding: 20rpx;
    background-color: #F7F8FA;
    border-radius: 12rpx;
    text-align: center;

    .week-day {
      font-size: 28rpx;
      color: #666;
      display: block;
    }

    .week-value {
      font-size: 32rpx;
      font-weight: 500;
      display: block;
      margin: 8rpx 0;

      &.normal {
        color: #91CB74;
      }

      &.high {
        color: #EE6666;
      }

      &.low {
        color: #3B82F6;
      }
    }

    .week-time {
      font-size: 24rpx;
      color: #999;
      display: block;
    }
  }
}

/* 图表容器 */
.qiun-charts {
  display: block;
  width: 100%;
  height: 400rpx;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.95);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;

  .loading-content {
    text-align: center;
    padding: 30rpx;
    border-radius: 20rpx;
    background-color: rgba(255, 255, 255, 0.8);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

    .loading-icon {
      margin-bottom: 20rpx;
      animation: rotate 1s linear infinite;
    }

    .loading-text {
      font-size: 28rpx;
      color: #666;
      font-weight: 500;
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>